import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ball_lion/module/team/basketball/lq_team_lineup_logic.dart';
import 'package:ball_lion/entity/team/lq_team_player_entity.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/resources/styles.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/widgets/bottom_picker_widget.dart';
import 'package:ball_lion/widgets/loading/no_data_widget.dart';

import 'package:ball_lion/widgets/base/wqs_text.dart';

class LqTeamLineupView extends StatefulWidget {
  const LqTeamLineupView({super.key});

  @override
  State<LqTeamLineupView> createState() => _LqTeamLineupViewState();
}

class _LqTeamLineupViewState extends State<LqTeamLineupView> {
  LqTeamLineupLogic logic =
      Get.put(LqTeamLineupLogic(), tag: '${Get.arguments}');
  List<String> tableTitle = [
    '球员',
    '得分',
    '篮板',
    '助攻',
    '抢断',
    '盖帽',
    '投篮%',
    '三分%',
    '罚球%'
  ];

  @override
  Widget build(BuildContext context) {
    return GetBuilder<LqTeamLineupLogic>(
      tag: '${Get.arguments}',
      builder: (_) {
        return Container(
          color: Colours.greyF7,
          child: MediaQuery.removePadding(
            context: context,
            removeTop: true,
            child: logic.yearData == null
                ? Container()
                : (logic.yearData!.isEmpty
                    ? const NoDataWidget()
                    : Column(
                        children: [
                          if (logic.nation == 1) _pageChoice(),
                          Expanded(
                            child: ListView(
                              children: [
                                // SizedBox(height: 10),
                                Container(
                                  decoration: const BoxDecoration(
                                      color: Colours.white,
                                      borderRadius:
                                          BorderRadius.all(Radius.circular(8))),
                                  margin: const EdgeInsets.symmetric(
                                      vertical: 10, horizontal: 12),
                                  padding: const EdgeInsets.all(16),
                                  child: Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        const QsText('球员数据',
                                            fontWeight: FontWeight.w500,
                                            fontSize: 16),
                                        const SizedBox(height: 16),
                                        filterWidget(),
                                        const SizedBox(height: 10),
                                        lineup(),
                                      ]),
                                ),
                                const SizedBox(height: 50)
                              ],
                            ),
                          ),
                        ],
                      )),
          ),
        );
      },
    );
  }

  Widget _pageChoice() {
    return Container(
      color: Colours.white,
      padding: const EdgeInsets.only(left: 12, right: 8, top: 5, bottom: 5),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          GestureDetector(
            onTap: selectYear,
            child: Container(
              height: 24,
              width: 58,
              alignment: Alignment.center,
              padding: const EdgeInsets.only(left: 6, right: 2),
              decoration: BoxDecoration(
                  color: Colours.greyF5F7FA,
                  borderRadius: BorderRadius.circular(15)),
              child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    QsText(
                        Utils.parseYear(
                            logic.yearData![logic.yearIndex].seasonYear ?? ''),
                        needCenter: true,
                        fontSize: 12,
                        color: Colours.text),
                    const SizedBox(width: 2),
                    Padding(
                      padding: const EdgeInsets.only(top: 2),
                      child: Image.asset(
                        Utils.getImgPath('down_arrow.png'),
                        width: 8,
                        height: 6,
                      ),
                    )
                  ]),
            ),
          ),
          Container(width: 5),
          Expanded(
            child: SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child: Row(
                mainAxisSize: MainAxisSize.min,
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: List.generate(
                    logic.yearData![logic.yearIndex].leagueInfo!.length,
                    (childIndex) => Flexible(
                          flex: 1,
                          child: GestureDetector(
                            onTap: () async {
                              logic.changeLeague(childIndex);
                            },
                            child: Container(
                              height: 24,
                              alignment: Alignment.center,
                              padding:
                                  const EdgeInsets.symmetric(horizontal: 15),
                              decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(30),
                                  color: logic.leagueIndex == childIndex
                                      ? Colours.redFFECEE
                                      : Colours.white),
                              child: QsText(
                                logic.yearData![logic.yearIndex]
                                        .leagueInfo![childIndex].leagueName ??
                                    "",
                                color: logic.leagueIndex == childIndex
                                    ? Colours.main
                                    : Colours.grey66,
                                needCenter: true,
                              ),
                            ),
                          ),
                        )),
              ),
            ),
          ),
        ],
      ),
    );
  }

  filterWidget() {
    return Row(
      children: [
        Expanded(
          child: SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            child: Row(
              children: List.generate(
                  logic.yearData![logic.yearIndex]
                      .leagueInfo![logic.leagueIndex].scope!.length, (index) {
                return GestureDetector(
                  onTap: () {
                    logic.changeScope(index);
                  },
                  child: Container(
                      margin: const EdgeInsets.only(right: 10),
                      padding: const EdgeInsets.symmetric(horizontal: 8),
                      height: 22,
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(11),
                          color: logic.scopeIndex == index
                              ? Colours.main
                              : Colours.greyF5F5F5),
                      // width: 52,
                      child: QsText(
                        (logic
                                    .yearData![logic.yearIndex]
                                    .leagueInfo![logic.leagueIndex]
                                    .scope![index]
                                    .scopeName ??
                                '') +
                            (logic
                                    .yearData![logic.yearIndex]
                                    .leagueInfo![logic.leagueIndex]
                                    .scope![index]
                                    .stageName ??
                                ''),
                        color: logic.scopeIndex == index
                            ? Colours.white
                            : Colours.grey66,
                        fontSize: 12,
                      )),
                );
              }),
            ),
          ),
        ),
        if (logic.nation == 0) ...[
          const SizedBox(width: 10),
          SizedBox(
              height: 22,
              width: 61,
              child: _selectButton(
                  Utils.parseYear(
                      logic.yearData![logic.yearIndex].seasonYear ?? ''),
                  selectYear))
        ],
      ],
    );
  }

  Widget lineup() {
    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      child: Table(
        defaultColumnWidth: const FixedColumnWidth(40),
        columnWidths: const {
          0: FixedColumnWidth(141),
          6: FixedColumnWidth(52),
          7: FixedColumnWidth(52),
          8: FixedColumnWidth(52),
        },
        children: [
          TableRow(
              children: List.generate(tableTitle.length, (index) {
            TextAlign align = TextAlign.center;
            if (index == 0) {
              align = TextAlign.left;
            }
            return TableCell(
                child: Padding(
              padding: const EdgeInsets.symmetric(vertical: 6),
              child: QsText(tableTitle[index],
                  fontSize: 12, color: Colours.grey66, textAlign: align),
            ));
          })),
          ...List.generate(logic.list!.length, (index) {
            LqTeamPlayerEntity player = logic.list![index];
            return TableRow(
                children: List.generate(9, (index1) {
              Widget widget;
              if (index1 == 0) {
                widget = Padding(
                  padding: const EdgeInsets.symmetric(vertical: 9),
                  child: Row(
                    children: [
                      CachedNetworkImage(
                        imageUrl: player.logo ?? '',
                        width: 24,
                        height: 32,
                        fit: BoxFit.cover,
                        placeholder: (context, url) => Styles.placeholderIcon(),
                        errorWidget: (context, url, error) => Image.asset(
                          Utils.getImgPath('lq_placeholder.png'),
                          height: 32,
                          width: 24,
                        ),
                      ),
                      const SizedBox(width: 8),
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            QsText(
                              player.nameZhShort ?? '',
                              fontSize: 13,
                            ),
                            const SizedBox(height: 2),
                            QsText(
                                '${player.shirtNumber}号 ${Utils.bbPositionName(player.position)}',
                                fontSize: 11,
                                color: Colours.grey66)
                          ],
                        ),
                      )
                    ],
                  ),
                );
              } else {
                String text = '';
                if (index1 == 1) {
                  text = '${player.points ?? '-'}';
                } else if (index1 == 2) {
                  text = '${player.rebounds ?? '-'}';
                } else if (index1 == 3) {
                  text = '${player.assists ?? '-'}';
                } else if (index1 == 4) {
                  text = '${player.steals ?? '-'}';
                } else if (index1 == 5) {
                  text = '${player.blocks ?? '-'}';
                } else if (index1 == 6) {
                  text = player.fieldGoalsAccuracy ?? '-';
                } else if (index1 == 7) {
                  text = player.threePointsAccuracy ?? '-';
                } else if (index1 == 8) {
                  text = player.freeThrowsAccuracy ?? '-';
                }
                widget = QsText(
                  text,
                  textAlign: TextAlign.center,
                  fontSize: 13,
                );
              }
              return TableCell(
                  verticalAlignment: TableCellVerticalAlignment.middle,
                  child: widget);
            })

                // controller.vsList!.map((e) {
                //   return TableCell(child: QsText(e));
                // }).toList());
                );
          })
        ],
      ),
    );
  }

  Widget _selectButton(String title, Function f) {
    return TextButton(
        style: ButtonStyle(
          padding: MaterialStateProperty.all(EdgeInsets.zero),
          side: MaterialStateProperty.all<BorderSide>(
            const BorderSide(width: 0.5, color: Colours.grey66),
          ),
          shape: MaterialStateProperty.all<OutlinedBorder>(
            RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12),
            ),
          ),
        ),
        onPressed: () => f(),
        child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [
          QsText(
            title,
            fontSize: 12,
            color: Colours.grey66,
          ),
          const SizedBox(width: 4),
          Image.asset(
            Utils.getImgPath('down_arrow.png'),
            width: 8,
            height: 6,
          )
        ]));
  }

  void selectYear() async {
    final yearList =
        logic.yearData!.map((e) => Utils.parseYear(e.seasonYear!)).toList();
    final result = await Get.bottomSheet(BottomPickerWidget(
      yearList,
      title: '选择年份',
      initialIndex: logic.yearIndex,
    ));
    if (result != null) {
      logic.changeYear(result);
    }
  }
}
